#include "udpServer.hpp"

#include <memory>

using namespace Server;


// 提示 运行格式
static void Usage(string proc)
{
    cout<<"Usage:\n\t" << proc <<" local_port\n\n";
}

//1.
void handlerMessage(int sockfd,string Clientip,uint16_t Clientport,string message)
{

    string response_message = message;
    response_message += " [server echo]";
    
    //开始返回
    struct sockaddr_in client;
    bzero(&client,sizeof(client));

    client.sin_family = AF_INET;
    client.sin_port = htons(Clientport);
    client.sin_addr.s_addr = inet_addr(Clientip.c_str());

    sendto(sockfd,response_message.c_str(),response_message.size(),0,(struct sockaddr*)&client,sizeof(client));

}

//  ./udpServer port
int main(int argc,char* argv[])
{
    if(argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    uint16_t port = atoi(argv[1]);
    // string ip = argv[1];

    unique_ptr<udpServer> usvr(new udpServer(handlerMessage,port)); //1.


    usvr->initServer(); //初始化服务器
    usvr->start();      //运行服务器

    return 0;
}